from socket import *
import time

COD = "utf-8"
HOST = "127.0.0.1"
# 端口号
PORT = 21566
BUFSIZE = 1024
ADDR = (HOST, PORT)
SIZE = 10
# 创建socket对象
tcpS = socket(AF_INET, SOCK_STREAM)
# 加入socket配置，重用ip和端口
tcpS.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# 绑定ip端口
tcpS.bind(ADDR)
# 设置最大连接数
tcpS.listen(SIZE)

print("服务器启动，监听客户端连接。")
while True:
    conn, addr = tcpS.accept()
    print("客户端连接：", addr)
    while True:
        try:
            # 读取已连接客户端的发送信息
            data = conn.recv(BUFSIZE)
        except Exception:
            print("客户端断开连接：", addr)
            break
        print("客户端", addr, "发送的内容：", data.decode(COD))
        if not data:
            break
        # 获取结构化事件戳
        msg = time.strftime("%Y-%m-%d %X")
        msg1 = '[%s] >> %s' %(msg, data.decode(COD))
        # 发送消息给已连接客户端
        conn.send(msg1.encode(COD))
    conn.close()
    print("客户端退出：", addr)
tcpS.close()
